<template>
  <section class='f-meal-detail'>
    <img class="f-img" :src="formData.image? formData.image: defaultMealImg" alt="">
    <img class="f-return-img" src="@/assets/icons/return_btn_return.png" alt="" @click="goBack()">

    <section class="f-card">
      <p class="f-title">{{ formData.packageName }}</p>
      <p class="f-price">CNY {{ (formData.price/10/10).toFixed(2) }}</p>
      <div class="f-flex-between">
        <p>流量</p>
        <p>{{ bytesToSize(formData.traffic,1) }}</p>
      </div>
      <div class="f-flex-between f-mt-05">
        <p>有效期</p>
        <p>{{formData.period}}天</p>
      </div>
    </section>

    <section class="f-card">
      <p class="f-title">适用区域</p>
      <p class="f-mt-20">{{formData.applicableArea}}</p>
    </section>

    <section class="f-card">
      <p class="f-title">套餐描述</p>
      <p class="f-mt-20">{{ formData.remark }}</p>
    </section>

    <section class="f-card" style="margin-bottom: 60px">
      <p class="f-title">使用须知</p>
      <p class="f-mt-20" style="white-space: pre-line;line-height: 25px;">{{formData.hints || '--'}}</p>
    </section>

    <section class="f-buy">
      <p>CNY {{ (formData.price/10/10).toFixed(2) }}</p>
      <van-button color="#1FC10B" round size="small" style="padding: 5px 25px" @click="popup = true">购买</van-button>
    </section>

    <van-popup v-model:show="popup" position="bottom" round class="f-popup" closeable @close="closePopup()">
      <p class="f-title">套餐订购</p>
      <section class="f-card">
        <p>用户码</p>
        <p class="f-mt-10">
          <span>{{code || '--'}}</span>
        </p>
      </section>

      <section class="f-card">
        <p class="f-card-title">
          <span>套餐内容</span>
          <span style="color: #FF3F3F;">CNY {{ (formData.price/10/10).toFixed(2) }}</span>
        </p>
        <div class="f-content">
          <p class="p">{{ formData.packageName }}</p>
          <p class="p">{{ formData.remark }}</p>
        </div>
      </section>

      <!-- <section class="f-card">
        <p class="f-card-title">
          <span>数量</span>
          <van-stepper v-model="formData.num" max="100" />
        </p>
      </section> -->

      <section class="f-card">
        <p class="f-card-title">
          <span>付款方式</span>
        </p>
        <div class="f-content">
          <van-radio-group v-model="orderForm.payType" shape="dot">
            <van-radio :name="1" label-position="left" icon-size="16px" style="margin-top: 15px;">
              <div class="f-pay-box">
                <img src="@/assets/icons/withdraw_icon_wx.png" alt="">
                <p>微信支付</p>
              </div>
            </van-radio>
            <van-radio :name="3" label-position="left" icon-size="16px" style="margin-top: 15px;">
              <div class="f-pay-box">
                <img src="@/assets/icons/withdraw_icon_zfb.png" alt="">
                <p>支付宝支付</p>
              </div>
            </van-radio>
          </van-radio-group>
        </div>
      </section>

      <div class="f-agreement">
        <van-checkbox v-model="checked" checked-color="#3366FF" icon-size="16px">
          我已阅读并同意
          <span style="color: #3967D9;">《全讯物联充值协议》</span>
        </van-checkbox>
      </div>

      <div class="f-bottom-box">
        <div class="g-flex-ct f-price">
          <p style="color: #0B0000;font-size: 14px;">合计</p>
          <p class="f-ml-10">CNY {{ (formData.price/10/10).toFixed(2) }}</p>
        </div>
        <van-button type="primary" round size="small" @click="yklOrderSubmit()">
          <p style="padding: 20px 30px">去支付</p>
        </van-button>
      </div>
    </van-popup>
  </section>
</template>
  
<script>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import api from './api';
import { errorDeal, getStore, successDeal } from '@/utils/utils';
import JsBridge from '@/utils/JsBridge.js'

export default {
  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const state = reactive({
      code: getStore('CURRENT_CODE').code,
      formData: getStore('yklPackDetail'),

      packId: route.query.packId,

      defaultMealImg: require('@/assets/imgs/pic_package_default.png'),

      popup: false,
      checked: false,

      fromUserId: route.query.fromUserId,
      orderForm: {
        "openId": "",
        "payType": 100, // 支付方式，1-微信app，2-微信扫码支付，3-支付宝APP支付，6-微信JSAPI支付，7-支付宝网页支付，8-微信H5，9-支付宝手机网站支付,100-账户余额支付
        "returnUrl": "",
        "sysOrderId": ""
      },

      sysOrderId: '',

      balance: 0,
    })

    onMounted(() => {
      store.commit("setNavBar", {
        title: '套餐详情',
        show: false,
        left: true,
        leftType: 'back',
        right: false,
        rightText: '',
      });

      getYklPackDetail()
    })

    const getYklPackDetail = () => {
      let json = {
        packId: state.packId
      }
      api.yklPackDetail(json).then(res => {
        state.formData = res.data
      })
    }

    // 下单
    const yklOrderSubmit = () => {
      if (!state.code) {
        errorDeal("请输入用户码")
        return
      }
      if (!state.checked) {
        errorDeal("请阅读并同意服务协议")
        return
      }
      let json = {
        "code": state.code,
        num: 1,
        "packageId": state.packId
      }
      api.yklOrderSubmit(json).then(res => {
        state.sysOrderId = res.data.sysOrderId
        if (res.data.topay) {
          onSubmit(res.data)
        } else {
          toOrderDetail()
        }
      })
    }

    // 支付
    const yklOrderPay = (data) => {
      let json = JSON.parse(JSON.stringify(state.orderForm))
      json.sysOrderId = data.sysOrderId
      api.yklOrderPay(json).then(res => {
        successDeal('支付成功')
        state.popup = false
      })
    }

    const onSubmit = () => {
      if (state.fromUserId) {
        /**
         * h5支付
         */
        let json = {
          "openId": state.openId,
          "payType": '', // 	支付方式，2：微信扫码支付，6：微信JSAPI支付，7：支付宝网页支付，8:微信H5，9：支付宝手机网站支付
          "returnUrl": `${location.origin}/app/#/order/success?sysOrderId=${route.query.sysOrderId}&type=2&fromUserId=${state.fromUserId}`,
          "sysOrderId": route.query.sysOrderId
        }
        if (state.orderForm.payType == 1) {
          json.payType = 6
        }
        if (state.orderForm.payType == 3) {
          json.payType = 9
        }

        api.goodsPayH5(json).then(res => {
          // 微信支付
          if (state.orderForm.payType == 1) {
            wxTopay(res.data)
          }

          // 支付宝支付
          if (state.orderForm.payType == 3) {
            // 将接口返回的Form表单显示到页面
            document.querySelector('body').innerHTML = res.data.payQRCode; // res.data就是支付宝返回给你的form
            //调用submit 方法
            document.forms[0].submit()
          }
        })
      } else {
        /**
         * app内支付
         */
        let json = {
          "openId": "",
          "payType": state.orderForm.payType,
          "returnUrl": "",
          "sysOrderId": state.sysOrderId
        }
        api.yklOrderPay(json).then(res => {
          // 微信支付
          if (state.orderForm.payType == 1) {
            JsBridge.callHandler('wxpay', res.data, (res1) => {
              try {
                let data = JSON.parse(res1)
                const { success } = data
                if (success) {
                  toOrderDetail()
                } else {
                  errorDeal('支付失败！')
                }
              } catch {
                errorDeal('支付失败！')
              }
            })
          }

          // 支付宝支付
          if (state.orderForm.payType == 3) {
            JsBridge.callHandler('alipay', res.data.payQRCode, (res1) => {
              try {
                let data = JSON.parse(JSON.parse(res1).msg)
                if (data.alipay_trade_app_pay_response.code == 10000) {
                  toOrderDetail()
                } else {
                  errorDeal('支付失败！')
                }
              } catch {
                errorDeal('支付失败！')
              }
            })
          }

          // 余额支付
          if (state.orderForm.payType == 100 && res.data.result) {
            toOrderDetail()
          }
        })
      }
    }

    const toOrderDetail = () => {
      successDeal('支付成功！')
      setTimeout(() => {
        router.replace({
          path: "/outChina/rechargeRecordDetail",
          query: {
            sysOrderId: state.sysOrderId
          }
        })
      }, 500)
    }

    const closePopup = () => {
      state.formData.num = 1
    }

    const goBack = () => {
      router.go(-1)
    }

    const bytesToSize = function (bytes, decimal) {
      if (bytes === 0) return "0 MB";
      if (bytes == undefined || bytes == null) return "--"
      var k = 1024; // or 1024
      var sizes = ["MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
      var i = Math.floor(Math.log(bytes) / Math.log(k));

      return (bytes / Math.pow(k, i)) + " " + sizes[i];
    }


    return {
      ...toRefs(state),
      bytesToSize,
      yklOrderSubmit,
      closePopup,
      goBack
    }
  }
}
</script>
  
<style lang='scss' scoped>
.f-meal-detail {
  padding: 14px;
  position: relative;
  z-index: 1;
  padding-top: 330px;
  .f-img {
    position: absolute;
    width: 375px;
    height: 375px;
    left: 0;
    top: 0;
    z-index: -1;
    object-fit: cover;
  }
  .f-return-img {
    position: fixed;
    width: 32px;
    top: 43px;
    left: 13px;
  }
  .f-card {
    background: #ffffff;
    border-radius: 13px;
    padding: 13px 11px;
    font-size: 14px;
    color: #666666;
    margin-bottom: 14px;
    z-index: 2;
    .f-title {
      font-size: 16px;
      color: #333333;
    }
    .f-price {
      color: #fa4d49;
      margin: 10px 0;
      border-bottom: 1px solid #ececec;
      padding-bottom: 10px;
      font-size: 550;
    }
  }
  .f-buy {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 14px 20px 14px;
    border-top: 1px solid #dcdcdc;
    font-size: 14px;
    color: #fa4d49;
    font-size: 550;
  }
  .f-popup {
    .f-title {
      font-weight: 500;
      font-size: 16px;
      color: #000000;
      text-align: center;
      padding: 14px 0 0px 0;
    }
    .f-card {
      width: 347px;
      background: rgba(255, 255, 255, 0.7);
      border-radius: 13px;
      margin: 14px;
      font-weight: 500;
      font-size: 14px;
      color: #0b0000;
      padding: 17px 15px 20px 20px;
      .f-card-title {
        font-weight: 500;
        font-size: 14px;
        color: #0b0000;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      .f-content {
        margin-top: 20px;
        font-weight: 400;
        font-size: 12px;
        color: #424242;
        .p {
          height: 20px;
        }
        .f-pay-box {
          display: flex;
          align-items: center;
          font-weight: 400;
          font-size: 14px;
          color: #000000;
          width: 280px;
          img {
            width: 30px;
            height: 30px;
            margin-right: 10px;
          }
        }
      }
    }
    .f-agreement {
      display: flex;
      align-items: center;
      font-weight: 300;
      font-size: 12px;
      color: #424242;
      margin: 12px 24px;
    }
    .f-bottom-box {
      width: 375px;
      background: #ffffff;
      box-shadow: -2px 0px 7px 1px rgba(171, 171, 171, 0.85);
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 14px 17px 20px 17px;
      .f-price {
        font-weight: 500;
        font-size: 16px;
        color: #ff3f3f;
      }
    }
  }
}
</style>